<!-- 文件上传组件 -->
<template>
  <div style="width: 100%">
    <div class="upload-actions">
      <el-upload
        v-model:file-list="fileList"
        :style="props.style"
        :before-upload="handleBeforeUpload"
        :http-request="handleUpload"
        :on-progress="handleProgress"
        :on-success="handleSuccess"
        :on-error="handleError"
        :accept="props.accept"
        :limit="props.limit"
        multiple
      >
        <!-- 上传文件按钮 -->
        <el-button type="primary" :disabled="fileList.length >= props.limit">
          {{ props.uploadBtnText }}
        </el-button>

        <!-- 文件列表 -->
        <template #file="{ file }">
          <div class="el-upload-list__item-info">
            <div v-if="file.status === 'uploading'" class="upload-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>上传中...</span>
            </div>
            <template v-else>
              <a class="el-upload-list__item-name" @click="handleDownload(file)">
                <el-icon><Document /></el-icon>
                <span class="el-upload-list__item-file-name">{{ file.name }}</span>
                <span class="el-icon--close" @click.stop="handleRemove(file.url)">
                  <el-icon><Close /></el-icon>
                </span>
              </a>
            </template>
          </div>
        </template>
      </el-upload>

      <!-- 下载按钮 -->
      <el-button type="success" :disabled="fileList.length === 0" @click="handleDownloadAll">
        下载全部
      </el-button>
    </div>

    <el-progress
      :style="{
        display: showProgress ? 'inline-flex' : 'none',
        width: '100%',
      }"
      :percentage="progressPercent"
    />
  </div>
</template>

<script setup>
import FileAPI from "@/api/file.api";
import { ref, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { Document, Close, Loading } from "@element-plus/icons-vue";

const props = defineProps({
  /**
   * 请求携带的额外参数
   */
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  /**
   * 上传文件的参数名
   */
  name: {
    type: String,
    default: "file",
  },
  /**
   * 文件上传数量限制
   */
  limit: {
    type: Number,
    default: 10,
  },
  /**
   * 单个文件上传大小限制(单位MB)
   */
  maxFileSize: {
    type: Number,
    default: 10,
  },
  /**
   * 上传文件类型
   */
  accept: {
    type: String,
    default: "*",
  },
  /**
   * 上传按钮文本
   */
  uploadBtnText: {
    type: String,
    default: "上传文件",
  },

  /**
   * 样式
   */
  style: {
    type: Object,
    default: () => {
      return {
        width: "300px",
      };
    },
  },
});

const modelValue = defineModel("modelValue", {
  type: String,
  default: () => "[]",
});

const fileList = ref([]);
const parsedData = ref([]);
// 防止重复渲染的锁
const updating = ref(false);

const showProgress = ref(false);
const progressPercent = ref(0);

// 解析JSON字符串
const parseModelValue = () => {
  try {
    if (!modelValue.value) {
      parsedData.value = [];
      return [];
    }

    const parsed = JSON.parse(modelValue.value);
    if (Array.isArray(parsed)) {
      parsedData.value = parsed;
      return parsed;
    }
    parsedData.value = [];
    return [];
  } catch (error) {
    console.error("解析JSON字符串失败:", error);
    parsedData.value = [];
    return [];
  }
};

// 更新modelValue，但不触发重复渲染
const updateModelValue = () => {
  if (updating.value) return;
  updating.value = true;

  nextTick(() => {
    modelValue.value = JSON.stringify(parsedData.value);
    updating.value = false;
  });
};

// 从parsedData同步到fileList，避免完全重置
const syncFileList = () => {
  const existingFiles = new Set(fileList.value.map((file) => file.url));
  const newFiles = [];

  // 处理已有文件
  parsedData.value.forEach((item) => {
    if (item.url) {
      // 如果文件已在列表中，保留它，不做修改
      if (!existingFiles.has(item.url)) {
        newFiles.push({
          name: item.name || item.url?.substring(item.url.lastIndexOf("/") + 1) || "未命名",
          url: item.url,
          status: "success",
          uid: getUid(),
        });
      }
    }
  });

  // 添加新文件到列表末尾，不重置整个列表
  if (newFiles.length > 0) {
    fileList.value.push(...newFiles);
  }
};

// 监听 modelValue 转换用于显示的 fileList
watch(
  modelValue,
  () => {
    if (updating.value) return;
    parseModelValue();

    // 不再一次性重置fileList，而是智能同步
    if (fileList.value.length === 0) {
      // 初始化时完整赋值
      fileList.value = parsedData.value.map((item) => ({
        name: item.name || item.url?.substring(item.url.lastIndexOf("/") + 1) || "未命名",
        url: item.url,
        status: "success",
        uid: getUid(),
      }));
    } else {
      // 后续变更只同步差异部分
      syncFileList();
    }
  },
  { immediate: true }
);

/**
 * 上传前校验
 */
function handleBeforeUpload(file) {
  // 限制文件大小
  if (file.size > props.maxFileSize * 1024 * 1024) {
    ElMessage.warning("上传文件不能大于" + props.maxFileSize + "M");
    return false;
  }
  return true;
}

/*
 * 上传文件
 */
function handleUpload(options) {
  const file = options.file;

  // 确保文件状态正确设置为 uploading
  const uploadingFile = fileList.value.find((f) => f.uid === file.uid);
  if (uploadingFile) {
    uploadingFile.status = "uploading";
  } else {
    // 手动添加上传文件到列表
    fileList.value.push({
      name: file.name,
      uid: file.uid,
      status: "uploading",
    });
  }

  return new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append(props.name, file);

    // 处理附加参数
    Object.keys(props.data).forEach((key) => {
      formData.append(key, props.data[key]);
    });

    FileAPI.upload(formData)
      .then((data) => {
        resolve({
          ...data,
          uid: file.uid,
        });
      })
      .catch((error) => {
        // 移除上传失败的文件
        const index = fileList.value.findIndex((f) => f.uid === file.uid);
        if (index !== -1) {
          fileList.value.splice(index, 1);
        }
        reject(error);
      });
  });
}

/**
 * 上传进度
 *
 * @param event
 */
const handleProgress = (event) => {
  progressPercent.value = event.percent;
};

/**
 * 上传成功
 */
const handleSuccess = (fileInfo, uploadFile) => {
  ElMessage.success("上传成功");

  // 找到当前上传的文件索引
  const index = fileList.value.findIndex((file) => file.uid === uploadFile.uid);
  if (index !== -1) {
    // 更新fileList - 只更新这一项，不重置整个列表
    fileList.value[index].url = fileInfo.url;
    fileList.value[index].status = "success";

    // 添加到parsedData - 直接添加这一项，不触发全列表更新
    const newItem = { name: uploadFile.name || fileInfo.name || "未命名", url: fileInfo.url };
    parsedData.value.push(newItem);

    // 通过 nextTick 延迟更新，避免视图闪烁
    nextTick(() => {
      updateModelValue();
    });
  }
};

/**
 * 上传失败
 */
const handleError = (error) => {
  console.error(error);
  ElMessage.error("上传失败");
};

/**
 * 删除文件
 */
function handleRemove(fileUrl) {
  FileAPI.delete(fileUrl).then(() => {
    // 从parsedData中删除
    const index = parsedData.value.findIndex((item) => item.url === fileUrl);
    if (index !== -1) {
      parsedData.value.splice(index, 1);
      updateModelValue();

      // 同步更新fileList - 直接删除对应项，不重置整个列表
      const fileIndex = fileList.value.findIndex((file) => file.url === fileUrl);
      if (fileIndex !== -1) {
        fileList.value.splice(fileIndex, 1);
      }
    }
  });
}

/**
 * 下载全部文件
 */
function handleDownloadAll() {
  if (fileList.value.length === 0) {
    ElMessage.warning("没有文件可下载");
    return;
  }

  // 显示下载进度提示
  ElMessage.info(`正在下载 ${fileList.value.length} 个文件...`);

  // 逐个下载文件，避免浏览器阻止多个弹窗
  const downloadFiles = async () => {
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i];
      try {
        // 使用延迟避免浏览器阻止
        if (i > 0) {
          await new Promise((resolve) => setTimeout(resolve, 500));
        }
        window.open(file.url, "_blank");
      } catch (error) {
        console.error(`下载文件 ${file.name} 失败:`, error);
      }
    }
    ElMessage.success("所有文件下载已启动");
  };

  downloadFiles();
}

/**
 * 下载单个文件
 */
function handleDownload(file) {
  if (file.url) {
    window.open(file.url, "_blank");
  }
}

/** 获取一个不重复的id */
function getUid() {
  // 时间戳左移13位（相当于乘以8192） + 4位随机数
  return (Date.now() << 13) | Math.floor(Math.random() * 8192);
}
</script>
<style lang="scss" scoped>
.upload-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}

.el-upload-list__item .el-icon--close {
  position: absolute;
  top: 50%;
  right: 5px;
  color: var(--el-text-color-regular);
  cursor: pointer;
  opacity: 0.75;
  transform: translateY(-50%);
  transition: opacity var(--el-transition-duration);
}

.upload-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px;
  color: var(--el-text-color-regular);

  .loading-icon {
    animation: loading-rotate 2s linear infinite;
    font-size: 16px;
    margin-bottom: 4px;
    color: var(--el-color-primary);
  }

  span {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

:deep(.el-upload-list) {
  margin: 0;
}

:deep(.el-upload-list__item) {
  margin: 0;
}

:deep(.el-upload-list__item.is-uploading) {
  opacity: 1 !important;
}

:deep(.el-upload-list) {
  transition: none !important;
}

:deep(.el-upload-list__item) {
  transition: none !important;
}
</style>
